import React from "react";
import { createHashHistory, createBrowserHistory } from "history";

import { Router, Routes, Route } from "./my-react-router";
export { Routes, Route };

export function HashRouter({ children }) {
  const historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createHashHistory();
  }

  const history = historyRef.current;
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  // 监听路径变化，就执行 setState
  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}

export function BrowserRouter({ children }) {
  const historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory();
  }
  const history = historyRef.current;
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  // 监听路径变化，就执行 setState
  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}
